// 定义extend组件
const extendComponent = {
    name: 'extend',
    functional: true,
    props: {
        render: {
            type: Function,
            required: true
        },
        params: {
            type: Object,
            default: function () { return {} }
        }
    },
    render: function (h, ctx) {
        const { props } = ctx;
        return props.render(h, props.params);
    }
};

// 定义EnhancedTable组件
const EnhancedTable = {
    name: 'EnhancedTable',
    components: { 'extend': extendComponent },
    template: `
    <el-table :data="data" v-bind="$attrs" v-on="$listeners" :border="border" :size="size" :key="renderKey">
      <template v-for="(column, index) of columns">
        <template v-if="column.render">
          <el-table-column v-bind="getColumnConfig(column)" :key="index">
            <template slot="header" slot-scope="scope">
              <extend :render="column.headerRender" :params="scope" v-if="column.headerRender"></extend>
              <span v-else>{{ column.label }}</span>
            </template>
            <template slot-scope="scope">
              <extend :render="column.render" :params="scope"></extend>
            </template>
          </el-table-column>
        </template>
        <template v-else>
          <el-table-column v-bind="getColumnConfig(column)" :key="index"></el-table-column>
        </template>
      </template>
    </el-table>
  `,
    props: {
        showSelectionColumn: {
            type: Boolean,
        },
        data: {
            type: Array,
            required: true
        },
        columns: {
            type: Array,
            required: true
        },
        defaultColumnConfig: {
            type: Object,
            default: function () { return {} }
        },
        border: {
            type: Boolean,
            default: false
        },
        size: {
            type: String,
            default: "medium"
        }
    },
    data: function () {
        return {
            renderKey: 0
        }
    },
    methods: {
        getColumnConfig: function (column) {
            let ret = Object.assign({}, this.defaultColumnConfig, column);
            ret.prop = ret.id || ret.prop;
            return ret;
        },
        updateRenderKey: function () {
            this.renderKey++
        }
    }
};

// 暴露组件到全局，方便使用
window.EnhancedTable = EnhancedTable;

// 提供自动注册函数
window.registerTableComponent = function () {
    if (window.Vue) {
        Vue.component('EnhancedTable', EnhancedTable);
        console.log('EnhancedTable组件已注册');
    } else {
        console.error('Vue未加载，无法注册组件');
    }
};